﻿using System.IO;
using iReaper.IndexService.Common.TaskEngine;
using iReaper.IndexService.Common;

namespace iReaper.IndexService.MSEvents
{
    public class SaveDiskTask : TaskBase
    {
        #region ITask Members
        private System.Xml.Serialization.XmlSerializer seri = new System.Xml.Serialization.XmlSerializer(typeof(EventItem));
        public SaveDiskTask()
        {
            //SimpleFSDirectory dir = new SimpleFSDirectory(new DirectoryInfo(@".\Index"));
            // m_writer = new IndexWriter(dir, new Lucene.Net.Analysis.CJK.CJKAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED);
            System.IO.DirectoryInfo contentDir = new System.IO.DirectoryInfo(Config.ContentFolder);
             if (!contentDir.Exists)
             {
                 contentDir.Create();
             }
        }

        public override void Start()
        {
            System.Threading.Thread entry = new System.Threading.Thread(Entry);
            entry.Start();
        }

        private void Entry()
        {
            while (true)
            {
                var item = GetItem();
                if (item == null)
                {
                    Done();
                    return;
                }
                item.EventTypeId = EventType.WWE;
                //Document doc = new Document();
                //// id
                //doc.Add(new Field("id", item.EventID, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                //// title
                //doc.Add(new Field("", item.Title, Field.Store.NO, Field.Index.ANALYZED));
                //// description
                //doc.Add(new Field("", item.Description, Field.Store.NO, Field.Index.ANALYZED));
                //// date
                //doc.Add(new Field("date", DateTools.DateToString(item.StartData, DateTools.Resolution.DAY), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                //// store
                //m_writer.AddDocument(doc);
                var strm = File.OpenWrite(Config.ContentFolder + item.EventID + ".xml");
                StreamWriter writer = new StreamWriter(strm, System.Text.Encoding.UTF8);
                seri.Serialize(writer, item);
                writer.Close();
                strm.Close();
                SetResult(item);
            }
        }

        #endregion
    }
}
